package com.fujimana.android.manacode.loalder;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fujimana.android.manacode.utils.Utils;

public class SourcesDirectory extends Sources {

	private int DEFAULT_BUFFER_SIZE = 1024 * 1024;

	private Map<String, File> entries;

	public SourcesDirectory(String file) {
		super(file);
		this.entries = new HashMap<String, File>();
	}

	public SourcesDirectory(String file, String encode) {
		super(file, encode);
		this.entries = new HashMap<String, File>();
	}

	@Override
	public byte[] getData(String entry) throws IOException {
		File file = this.entries.get(entry);

		if (file == null) {
			return null;
		}

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		FileInputStream fis = null;

		try {
			fis = new FileInputStream(file);

			byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
			int n = 0;

			while (-1 != (n = fis.read(buffer))) {
				out.write(buffer, 0, n);
			}
		} finally {
			Utils.close(fis);
			Utils.close(out);
		}

		return out.toByteArray();
	}

	@Override
	public void read() throws IOException {
		File dir = new File(getFile());
		resolv(dir);
	}

	@Override
	public List<String> getEntries() {
		List<String> ret = new ArrayList<String>(entries.keySet());
		Collections.sort(ret, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return o1.compareToIgnoreCase(o2);
			}
		});

		return Collections.unmodifiableList(ret);
	}

	private void resolv(File file) {

		if (file.isDirectory()) {
			for (File f : file.listFiles()) {
				resolv(f);
			}
		} else {
			if (filtering(file.getPath())) {
				this.entries.put(file.getPath(), file);
			}
		}

	}
}
